package org.ecloud.zuul.swagger;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

@Configuration
@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {

	private static Logger logger = LoggerFactory.getLogger(DocumentationConfig.class);
	@Value("${swagger.info.docs}")
	private String docs;
	@Value("${swagger.info.version}")
	private String version;
	
	private final RouteLocator routeLocator;

    public DocumentationConfig(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<Route> routes = routeLocator.getRoutes();
        
        if(routes == null){
        	return resources;
        }
        
        //在这里遍历的时候，可以排除掉敏感微服务的路由
        for(Route route : routes){
        	logger.debug("route id {}, route full path {}, route full path replace {}, version {}.", route.getId(), route.getFullPath(), route.getFullPath().replace("**", docs), version);
        	if(route.getPrefix().endsWith(route.getLocation())) {
        		// 过滤服务名直接生成的文档
        		continue;
        	}
        	resources.add(swaggerResource(route.getId(), route.getFullPath().replace("**", docs), version));
        }
        
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }

}
